package com.microweb.toastmaster.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import com.microweb.toastmaster.webapp.action.BaseFormController;
import com.microweb.toastmaster.model.Actor;
import com.microweb.toastmaster.service.ActorManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class ActorFormController extends BaseFormController {
    private ActorManager actorManager = null;

    public void setActorManager(ActorManager actorManager) {
        this.actorManager = actorManager;
    }
    public ActorFormController() {
        setCommandName("actor");
        setCommandClass(Actor.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        Actor actor = null;

        if (!StringUtils.isEmpty(id)) {
            actor = actorManager.getActor(id);
        } else {
            actor = new Actor();
        }

        return actor;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        Actor actor = (Actor) command;
        boolean isNew = (actor.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            actorManager.removeActor(actor.getId().toString());

            saveMessage(request, getText("actor.deleted", locale));
        } else {
            actorManager.saveActor(actor);

            String key = (isNew) ? "actor.added" : "actor.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editActor.html", "id", actor.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
